package {
	
	import flash.events.*;
	import flash.media.*;
	import flash.net.*;
	import flash.utils.Timer;
	
	public class Player extends EventDispatcher {
		
		private var sound:Sound;
		private var channel:SoundChannel;
		private var position:Number;
		
		private var SOUND_VOLUME:Number = 0.75;
		private var EVENT_SOUND_COMPLETED:String = "SOUND_COMPLETED";
		public var loaded:Boolean = false;
		public var loopNow:Boolean=false;
		public function Player() {
			// init
			sound = new Sound();
			position = 0;

		}
		public function load(str:String):void{
			sound.addEventListener(Event.COMPLETE, onSoundLoadComplete);
			sound.load(new URLRequest(str));
		}
		private function onSoundLoadComplete(e:Event):void{
			sound.removeEventListener(Event.COMPLETE, onSoundLoadComplete);
			loaded=true;
			if (loopNow)loop();
		}
		public function play():void {
			if (!loaded)return;
			channel = sound.play(position);
			channel.soundTransform = new SoundTransform(SOUND_VOLUME);
		}
		public function loop():void {
			/*if (!loaded)return;
			channel = sound.play(position,10000);
			channel.soundTransform = new SoundTransform(SOUND_VOLUME);
			trace("Player playing..");*/
			var timer:Timer;
			var channel:SoundChannel;
			
			timer = new Timer(sound.length-153); // remove the silence gap at the end of the song added by Flash, you may need to tweak this depending on your mp3 encoder
			timer.addEventListener("timer", function (e:Event):void { // hack to get around gap between loops
				channel= sound.play();
			});
			timer.start();
			
			var initialTimer:Timer = new Timer(0, 1); // hack to get around initial gap from playing the first time and the timer kicking in
			initialTimer.addEventListener("timer", function (e:Event):void {
				channel= sound.play();
				initialTimer = null;
			});	
			initialTimer.start();
		}
		
		public function pause():void {
			if (channel != null) {
				channel.stop();
				position = channel.position;
			}
		}
		
		public function setPosition(pos:Number):void {
			position = pos;
		}
		
		public function getPosition():Number {
			if (channel == null) {
				return 0;
			} else {
				return channel.position;
			}
		}
	}
}